//index.js
var app = getApp();
Page({
  data: {
    bg:'cloud://kehuafu1120-4ihff.6b65-kehuafu1120-4ihff/images/bg.png',
    remind: '加载中',
    angle: 0,
    shopLogo: 'cloud://kehuafu1120-4ihff.6b65-kehuafu1120-4ihff/images/shopLogo.png'
  },
  onLoad: function() {
    var that = this
    that.setData({
        background_color: app.globalData.globalBGColor,
        bgRed: app.globalData.bgRed,
        bgGreen: app.globalData.bgGreen,
        bgBlue: app.globalData.bgBlue
      }),
      console.log("检测token状态")
    //获取本地token
    var token = wx.getStorageSync('token')
    if (token != '') {
      this.checkToken(token)
    }
    console.log(token)
  },
  onReady: function() {
    var that = this;
    setTimeout(function() {
      that.setData({
        remind: ''
      });
    }, 1000);
    wx.onAccelerometerChange(function(res) {
      var angle = -(res.x * 30).toFixed(1);
      if (angle > 14) {
        angle = 14;
      } else if (angle < -14) {
        angle = -14;
      }
      if (that.data.angle !== angle) {
        that.setData({
          angle: angle
        });
      }
    });
  },
  //进入店铺
  bingGetUserInfo: function(e) {
    console.log("进入店铺：", e);
    if (e.detail.errMsg == 'getUserInfo:ok') {
      app.globalData.userInfo = e.detail.userInfo
      wx.showLoading({
        title: '正在加载...',
      })
      //注册
      wx.login({
        success(res) {
          console.log(res)
          var code = res.code
          wx.request({
            url: 'https://api.it120.cc/kehuafu/user/wxapp/register/simple',
            data: {
              code: code
            },
            success(res) {
              console.log("注册结果：", res)
              //获取token
              wx.login({
                success(res) {
                  wx.request({
                    url: 'https://api.it120.cc/kehuafu/user/wxapp/login',
                    data: {
                      code: res.code
                    },
                    success(res) {
                      console.log("返回Token:", res.data.data.token)
                      //本地存储Token
                      wx.setStorage({
                        key: 'token',
                        data: res.data.data.token,
                      })
                      //返回主页
                      wx.navigateBack()
                    }
                  })
                }
              })
            }
          })
        }
      })
    }
  },
  //检测token状态
  checkToken(token) {
    wx.request({
      url: 'https://api.it120.cc/kehuafu/user/check-token',
      data: {
        token: token
      },
      success(res) {
        console.log("Token是否有效：", res.data.msg)
        if (res.data.msg == 'success') {
          wx.redirectTo({
            url: '/pages/home/home',
          })
        }
      }
    })
  }
})